const WebSocketManager = {
    ws: null,
    reconnectAttempts: 0,
    reconnectTimer: null,
    heartbeatTimer: null,
    lastHeartbeatResponse: 0,

    connect(username) {
        if (this.ws && this.ws.readyState === WebSocket.OPEN) {
            console.log('WebSocket already connected');
            return;
        }

        const wsUrl = `ws://${window.location.host}/ws?username=${encodeURIComponent(username)}`;
        this.ws = new WebSocket(wsUrl);

        this.ws.onopen = () => {
            console.log('WebSocket connected');
            this.reconnectAttempts = 0;
            this.startHeartbeat();
        };

        this.ws.onmessage = (event) => {
            MessageHandler.handleMessage(event);
        };

        this.ws.onclose = () => {
            console.log('WebSocket closed');
            this.stopHeartbeat();
            
            // 尝试重连
            if (this.reconnectAttempts < Config.ws.maxReconnectAttempts) {
                this.scheduleReconnect();
            } else {
                console.log('Max reconnection attempts reached');
            }
        };

        this.ws.onerror = (error) => {
            console.error('WebSocket error:', error);
        };
    },

    scheduleReconnect() {
        if (this.reconnectTimer) {
            clearTimeout(this.reconnectTimer);
        }

        // 计算重连延迟时间（指数退避）
        const delay = Math.min(
            Config.ws.baseReconnectDelay * Math.pow(2, this.reconnectAttempts),
            Config.ws.maxReconnectDelay
        );

        console.log(`Scheduling reconnect attempt ${this.reconnectAttempts + 1} in ${delay}ms`);

        this.reconnectTimer = setTimeout(() => {
            console.log(`Attempting to reconnect (${this.reconnectAttempts + 1}/${Config.ws.maxReconnectAttempts})`);
            this.reconnectAttempts++;
            this.connect(UserManager.currentUser);
        }, delay);
    },

    disconnect() {
        if (this.ws) {
            this.ws.close();
            this.ws = null;
        }
        this.stopHeartbeat();
        if (this.reconnectTimer) {
            clearTimeout(this.reconnectTimer);
            this.reconnectTimer = null;
        }
        this.reconnectAttempts = 0;
    },

    sendMessage(message) {
        if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
            console.error('WebSocket is not connected');
            return false;
        }

        try {
            this.ws.send(JSON.stringify(message));
            return true;
        } catch (error) {
            console.error('Error sending message:', error);
            return false;
        }
    },

    startHeartbeat() {
        this.stopHeartbeat(); // 清除现有的心跳定时器

        this.heartbeatTimer = setInterval(() => {
            if (this.ws && this.ws.readyState === WebSocket.OPEN) {
                const now = Date.now();
                
                // 检查上次心跳响应时间
                if (this.lastHeartbeatResponse && 
                    now - this.lastHeartbeatResponse > Config.ws.heartbeatTimeout) {
                    console.log('Heartbeat timeout, reconnecting...');
                    this.ws.close();
                    return;
                }

                // 发送心跳
                this.sendMessage({
                    type: 'HEARTBEAT',
                    timestamp: now
                });
            }
        }, Config.ws.heartbeatInterval);
    },

    stopHeartbeat() {
        if (this.heartbeatTimer) {
            clearInterval(this.heartbeatTimer);
            this.heartbeatTimer = null;
        }
    },

    isConnected() {
        return this.ws && this.ws.readyState === WebSocket.OPEN;
    }
}; 